package com.satan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.satan.entity.SysMenu;
import com.satan.entity.response.ResCode;
import com.satan.entity.response.ResultEntity;
import com.satan.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName SysMenuController
 * @Description TODO
 * @date 2023/11/25 23:48
 * @Version 1.0
 */
@RestController
@RequestMapping("menu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询所有菜单树信息
     *
     * @return
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public ResultEntity list() {
        List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        List<SysMenu> sysMenuList = sysMenuService.buildTreeMenu(menuList);
        return ResultEntity.success(sysMenuList);
    }

    /**
     * 添加或者修改
     *
     * @param sysMenu
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add')" + "||" + "hasAuthority('system:menu: edit')")
    public ResultEntity saveOrUpdateMenu(@RequestBody SysMenu sysMenu) {
        boolean b = sysMenuService.saveOrUpdateMenu(sysMenu);
        if (b) {
            return ResultEntity.success(null);
        } else {
            return ResultEntity.fail(ResCode.UPDATE_ERROR);
        }
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public ResultEntity findById(@PathVariable(value = "id")Long id){
        SysMenu sysMenu = sysMenuService.getById(id);
        return ResultEntity.success(sysMenu);
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public ResultEntity deleteMenu(@PathVariable(value = "id")Long id){
        ResCode resCode=sysMenuService.deleteMenu(id);
        if (resCode==null){
            return ResultEntity.success(null);
        }else {
            return ResultEntity.fail(resCode);
        }
    }
}
